package cn.xfdzx.android.apps.shop.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.activity.login.OneLoginMainActivity;
import cn.xfdzx.android.apps.shop.adapter.SearchGoodsListRetailAdapter;
import cn.xfdzx.android.apps.shop.adapter.SearchHotRetailListAdapter;
import cn.xfdzx.android.apps.shop.adapter.SearchItemAdapter;
import cn.xfdzx.android.apps.shop.adapter.SearchShopListRetailAdapter;
import cn.xfdzx.android.apps.shop.adapter.SearchShopListRetailOpenAllAdapter;
import cn.xfdzx.android.apps.shop.adapter.SearchShopsAdapter;
import cn.xfdzx.android.apps.shop.adapter.remake.OrderDissatisfiedReasonAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.ConfirmGoodBeen;
import cn.xfdzx.android.apps.shop.bean.HomeSearchRetailGoodsBean;
import cn.xfdzx.android.apps.shop.bean.HomeSearchXFDGoodBeen;
import cn.xfdzx.android.apps.shop.bean.HotSearchBeen;
import cn.xfdzx.android.apps.shop.bean.HotSearchRetailBean;
import cn.xfdzx.android.apps.shop.bean.SearchBeen;
import cn.xfdzx.android.apps.shop.bean.SearchShopBean;
import cn.xfdzx.android.apps.shop.contract.HomeSearchContract;
import cn.xfdzx.android.apps.shop.contract.ItemClickListener;
import cn.xfdzx.android.apps.shop.presenter.HomeSearchPresenter;
import cn.xfdzx.android.apps.shop.sql.DatabaseAdaper;
import cn.xfdzx.android.apps.shop.util.CenterLayoutManager;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.KeybordUtil;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.Utils;
import cn.xfdzx.android.apps.shop.util.UtilsData;
import cn.xfdzx.android.apps.shop.video.VideoActivity;
import cn.xfdzx.android.apps.shop.view.CheckableTextView;
import cn.xfdzx.android.apps.shop.view.ShoppingCartAnimationView;
import cn.xfdzx.android.apps.shop.view.WordWrapView;

import static cn.xfdzx.android.apps.shop.activity.MainActivity.TYPE_IS_RETAIL;
import static cn.xfdzx.android.apps.shop.apps.Constants.APP_TOKEN;

/*零售新搜索页面*/
public class HomeSearch_NewRetailActivity extends BaseMvpActivity<HomeSearchPresenter> implements HomeSearchContract.View {

    @BindView(R.id.iv_home_back)
    ImageView ivHomeBack;//返回键
    @BindView(R.id.et_home_search)
    EditText etHomeSearch;//搜索内容框
    @BindView(R.id.iv_home_search_et_delete)
    ImageView ivHomeSearchEtDelete;//清除搜索内容
    @BindView(R.id.tv_home_search)
    TextView tvHomeSearchCancel;//搜索键
    @BindView(R.id.wwv_view)
    WordWrapView wordWrapView;//自动换行历史记录
    @BindView(R.id.wwv_view_resou)
    WordWrapView wwViewResou;//热搜历史记录
    @BindView(R.id.rl_search_history)
    RelativeLayout rlSearchHistory;//历史记录整体
    @BindView(R.id.rl_hot_search_goods)
    RelativeLayout rlHotSearchGoods;//热搜商品
    @BindView(R.id.tv_search_result_comprehensive_sequencing)
    CheckableTextView tvSearchResultComprehensiveSequencing;//综合排序
    @BindView(R.id.tv_search_result_sales)
    CheckableTextView tvSearchResultSales;//销量
    @BindView(R.id.tv_search_result_distance)
    CheckableTextView tvSearchResultDistance;//距离
    @BindView(R.id.tv_search_result_breaks_the_freight)
    CheckableTextView tvSearchResultPrice;//价格


    @BindView(R.id.ll_state)
    LinearLayout llState;

    @BindView(R.id.rl_search_type)
    RelativeLayout rlSearchType;//商品分类排序
    @BindView(R.id.rv_search_item_type)
    RecyclerView rvSearchItemType;//类别与商铺列表
    @BindView(R.id.rv_search_shops)
    RecyclerView rvSearchShops;//商铺列表
    @BindView(R.id.ll_hint)
    LinearLayout llHint;
    @BindView(R.id.tv_hint)
    TextView tvHint;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    @BindView(R.id.tv_all)//全部店铺
    TextView tv_all;
    @BindView(R.id.recycle_shop)
    RecyclerView recycle_shop;//横向店铺列表
    @BindView(R.id.img_openallshop)//全部店铺
    ImageView img_openallshop;
    @BindView(R.id.rv_allshop)
    RecyclerView rv_allshop;//网格布局全部店铺列表
    @BindView(R.id.rl_openall)//全部店铺
    RelativeLayout rl_openall;
    @BindView(R.id.rl_title)//收起点击
    RelativeLayout rl_title;
    @BindView(R.id.tv_shopcount)//全部店铺
    TextView tv_shopcount;//店铺数量
    @BindView(R.id.tv_shopabout)//全部店铺
    TextView tv_shopabout;
    @BindView(R.id.tv_line)//全部下线
    TextView tv_line;
    @BindView(R.id.rl_cart)//购物车布局
    RelativeLayout rl_cart;
    @BindView(R.id.tv_allgoodscount)//购物车种类数量
    TextView tv_allgoodscount;
    @BindView(R.id.recycle_hotsearch)
    RecyclerView recycle_hotsearch;//网格热搜列表

    private boolean isComprehensiveSequencing = true;
    private boolean isSales = false;
    private boolean isDistance = false;
    private boolean isPrice = false;

    private boolean isBreaksTheFreight = false;
    private boolean isHighQualityStores = false;
    private boolean isMembersRedEnvelope = false;
    private boolean isCommentsHighMarks = false;
    private DatabaseAdaper databaseAdaper;
    private ArrayList<String> searchList;

    private SearchItemAdapter searchItemAdapter;//分类与商店显示
    private SearchShopsAdapter searchShopsAdapter;//商铺列表

    private boolean is_history = false;
    private Dialog dialog;
    private int type = 0;//类别 0-零售 1-批发
    private int page;
    private int limit = Constants.LIMIT;//每页多少条
    private String sid = "";
    private String keyWrod = "";
    private String is_store = "0";//是否查询店铺，1查询
    private String priceOrder = "";
    private String salesOrder = "";
    private RelativeLayout.LayoutParams item_bar;
    private List<HomeSearchXFDGoodBeen.DataBean> mList = new ArrayList<>();
    private String user_curent_lng,user_curent_lat;
    private List<SearchShopBean.DataBean> searShopDate;
    private SearchShopListRetailAdapter searchShopListRetailAdapter;
    private SearchShopListRetailOpenAllAdapter searchShopListRetailOpenAllAdapter;
    private SearchGoodsListRetailAdapter searchGoodsListRetailAdapter;//零售搜索商品适配器
    private List<HomeSearchRetailGoodsBean.DataBean.GoodsBean> searchGoodsList = new ArrayList<>();
    private boolean isOpen;//是否展开全部店铺
    private int oldIndex = -1;//横向店铺上次点击的角标
    private int currentIndex;
    private String storeId = "";//店铺id
    private CenterLayoutManager hollayoutManager;
    private int sort = 1;//排序规则 1 => 综合排序 2 => 销量排序 3 => 距离排序 4 => 价格排序
    private int currentCount;//当前
    private int currentListIndex;//列表当前添加购物车的角标
    private List<HotSearchRetailBean.DataBean> hotSearch;
    private SearchHotRetailListAdapter searchHotRetailListAdapter;
    private String searchTitle;

    @Override
    public int getLayoutId() {
        return R.layout.activity_home_searchretail;
    }

    @Override
    public void initView() {
        type = TYPE_IS_RETAIL;
        if (type == 0) {
            is_store = "1";
        }
        initHigh();
        user_curent_lng = UtilsData.getPreference(this, "coordinates").getString("coordinates_lng");
        user_curent_lat = UtilsData.getPreference(this, "coordinates").getString("coordinates_lat");

        mPresenter = new HomeSearchPresenter();
        mPresenter.attachView(this);

        databaseAdaper = new DatabaseAdaper(this);
        searchList = databaseAdaper.findAll();

        //类别与商铺的adpter
        rvSearchItemType.setLayoutManager(new LinearLayoutManager(this));
        rvSearchItemType.setItemAnimator(new DefaultItemAnimator());
        searchItemAdapter = new SearchItemAdapter(this, rvSearchItemType, rlSearchType, type);

        rvSearchItemType.setAdapter(searchItemAdapter);
        // 商铺列表
        rvSearchShops.setLayoutManager(new LinearLayoutManager(this));
        rvSearchShops.setItemAnimator(new DefaultItemAnimator());
        searchShopsAdapter = new SearchShopsAdapter(this, mList, type);
        searchShopsAdapter.setOnItemClick(new SearchShopsAdapter.OnItemClick() {
            @Override
            public void setOnItemClick(View view, int position) {
                Intent intent;
                if (type == 0) {
                    intent = new Intent(HomeSearch_NewRetailActivity.this, ShopActivity.class);
                    intent.putExtra("shop_id", mList.get(position).getId() + "");
                } else {
                    intent = new Intent(HomeSearch_NewRetailActivity.this, XFDGoodsDeatailsActivity.class);
                    intent.putExtra("good_id", mList.get(position).getId() + "");
                }
                startActivity(intent);
            }
        });
        rvSearchShops.setAdapter(searchShopsAdapter);

        defultHistroyView();
        public_set();//默认选中
        dialog = Utils.addDialog(this, R.layout.dialog, R.string.are_you_sure_to_delete_all_history, R.string.confirm, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                searchList.clear();
                databaseAdaper.add(searchList);
                wordWrapView.removeAllViews();
                rlSearchHistory.setVisibility(View.GONE);
                dialog.dismiss();
            }
        });
        etHomeSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (llHint.getVisibility() == View.VISIBLE) {
                    llHint.setVisibility(View.GONE);
                }
                //搜索隐藏购物车，显示搜索按钮
                tvHomeSearchCancel.setVisibility(View.VISIBLE);
                rl_cart.setVisibility(View.GONE);
                if (editable.toString().trim().length() == 0) {
                    ivHomeSearchEtDelete.setVisibility(View.GONE);
                    if (searchList.size() != 0) {
                        rlSearchHistory.setVisibility(View.VISIBLE);
                    } else {
                        rlSearchHistory.setVisibility(View.GONE);
                    }
                    rlHotSearchGoods.setVisibility(View.VISIBLE);
                    rlSearchType.setVisibility(View.GONE);//商品分类排序
                    rvSearchItemType.setVisibility(View.GONE);
                } else {
                    ivHomeSearchEtDelete.setVisibility(View.VISIBLE);
                    rl_openall.setVisibility(View.GONE);
                    mPresenter.initData(editable.toString().trim(), type + "",user_curent_lng,user_curent_lat);
                    if (is_history) {
                        is_history = false;
                    } else {
                        rlSearchHistory.setVisibility(View.INVISIBLE);
                        rlHotSearchGoods.setVisibility(View.INVISIBLE);
                        rlSearchType.setVisibility(View.GONE);
                        rvSearchItemType.setVisibility(View.VISIBLE);
                    }
                }
            }
        });

        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                page = 1;
                requestGoodsSortList(true,true);
                //mPresenter.initSearchData(true, true,user_curent_lng,user_curent_lat, sid, page + "", limit + "", type + "", is_store, "", keyWrod, priceOrder, salesOrder, "");

            }
        });
        //mPresenter.initHotSearch();
        //请求热搜
        mPresenter.getRetailHotSearch();

        etHomeSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    ((InputMethodManager) etHomeSearch.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(HomeSearch_NewRetailActivity.this
                                            .getCurrentFocus().getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    // 搜索，进行自己要的操作...
//                    seachList(viewIndex);//这里是我要做的操作！
                    String search_text = etHomeSearch.getText().toString().trim();
                    if (search_text.isEmpty()){
                        Utils.toastMessage(HomeSearch_NewRetailActivity.this,"请输入关键字");
                    }else {
                        if (search_text.length() != 0) {
                            if (searchList.contains(search_text)) {
                                searchList.remove(searchList.indexOf(search_text));
                                searchList.add(0, search_text);
                            } else {
                                searchList.add(0, search_text);
                            }
                            databaseAdaper.add(searchList);
                            wordWrapView.removeAllViews();
                            defultHistroyView();
                            setData();
                        }
                        page = 1;

                        keyWrod = search_text;
                        priceOrder = "";
                        salesOrder = "";
                        sort = 1;
                        //请求店铺列表
                        requestShopList();
                        requestGoodsSortList(true,true);
                        //mPresenter.initSearchData(true, true, user_curent_lng, user_curent_lat, sid, page + "", limit + "", type + "", is_store, "", keyWrod, priceOrder, salesOrder, "");
                        //搜索隐藏购物车，显示搜索按钮
                        tvHomeSearchCancel.setVisibility(View.VISIBLE);
                        rl_cart.setVisibility(View.GONE);
                    }
                    return true;
                }
                return false;
            }
        });

        initRecycle();

    }

    private void initRecycle() {
        //热搜列表
        recycle_hotsearch.setLayoutManager(new GridLayoutManager(this,2));
        searchHotRetailListAdapter = new SearchHotRetailListAdapter(hotSearch);
        recycle_hotsearch.setAdapter(searchHotRetailListAdapter);

        hollayoutManager = new CenterLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        recycle_shop.setLayoutManager(hollayoutManager);
        searchShopListRetailAdapter = new SearchShopListRetailAdapter(searShopDate);
        recycle_shop.setAdapter(searchShopListRetailAdapter);
        searchShopListRetailAdapter.setItemClickListener(new SearchShopListRetailAdapter.OnItemOnClickListener() {
            @Override
            public void onItemClick(int position,int oldPosition) {
                oldIndex = oldPosition;
                currentIndex = position;
                hollayoutManager.smoothScrollToPosition(recycle_shop, new RecyclerView.State(), position);
                searchShopListRetailAdapter.notifyDataSetChanged();
                if (searShopDate.get(position).getId()==0){
                    storeId = "";
                }else {
                    storeId = searShopDate.get(position).getId()+"";
                }

                requestGoodsSortList(true,true);
                tv_all.setTextColor(getResources().getColor(R.color.color_393939));
                tv_line.setVisibility(View.INVISIBLE);
            }
        });

        rv_allshop.setLayoutManager(new GridLayoutManager(this,2));
        searchShopListRetailOpenAllAdapter = new SearchShopListRetailOpenAllAdapter(searShopDate);
        rv_allshop.setAdapter(searchShopListRetailOpenAllAdapter);
        //展开的店铺点击，顶部滑动到指定位置
        searchShopListRetailOpenAllAdapter.setItemClickListener(new SearchShopListRetailOpenAllAdapter.OnItemOnClickListener() {
            @Override
            public void onItemClick(int position,int oldPosition) {
                oldIndex = oldPosition;
                currentIndex = position;
                searShopDate.get(position).setCheck(true);
                if (oldPosition>=0){
                    searShopDate.get(oldPosition).setCheck(false);
                }

                if (searShopDate.get(position).getId()==0){
                    storeId = "";
                }else {
                    storeId = searShopDate.get(position).getId()+"";
                }
                hollayoutManager.smoothScrollToPosition(recycle_shop, new RecyclerView.State(), position);
                searchShopListRetailAdapter.notifyDataSetChanged();
                rl_openall.setVisibility(View.GONE);
                tv_all.setTextColor(getResources().getColor(R.color.color_393939));
                tv_line.setVisibility(View.INVISIBLE);
                requestGoodsSortList(true,true);
            }
        });

        searchGoodsListRetailAdapter = new SearchGoodsListRetailAdapter(searchGoodsList,mPresenter);
        // 商铺列表
        rvSearchShops.setLayoutManager(new LinearLayoutManager(this));
        rvSearchShops.setAdapter(searchGoodsListRetailAdapter);
        searchGoodsListRetailAdapter.setItemClickListener(new SearchGoodsListRetailAdapter.OnItemAddCartListener() {
            @Override
            public void onItemAddCartClick(int position, HomeSearchRetailGoodsBean.DataBean.GoodsBean date,ImageView view) {
                ShoppingCartAnimationView shoppingCartAnimationView = new ShoppingCartAnimationView(HomeSearch_NewRetailActivity.this);
                int postion[] = new int[2];
                view.getLocationInWindow(postion);
                shoppingCartAnimationView.setStartPosition(new Point(postion[0], postion[1]));
                ViewGroup rootView = (ViewGroup) getWindow().getDecorView();
                rootView.addView(shoppingCartAnimationView);
                int endPosition[] = new int[2];
                tv_allgoodscount.getLocationInWindow(endPosition);
                shoppingCartAnimationView.setEndPosition(new Point(endPosition[0], endPosition[1]));
                shoppingCartAnimationView.startBeizerAnimation();
                tv_allgoodscount.setAnimation(shakeAnimation(1));

                currentListIndex = position;
                Map<String,Object> map = new HashMap<>();
                map.put("is_new",0);
                map.put("productId",date.getId());
                map.put("cartNum",1);
                mPresenter.addCar(map);
            }
        });

    }

    public Animation shakeAnimation(int CycleTimes) {
        Animation animation = new ScaleAnimation(1.0f, 1.2f, 1.0f, 1.2f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
//        Animation translateAnimation = new TranslateAnimation(10, 10, 10, 10);
//        translateAnimation.setInterpolator(new CycleInterpolator(CycleTimes));
//        translateAnimation.setDuration(1000);
        animation.setInterpolator(new CycleInterpolator(CycleTimes));
        animation.setDuration(800);
        return animation;
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    private void initHigh() {
        item_bar = (RelativeLayout.LayoutParams) llState.getLayoutParams();
        item_bar.height = StatusBarUtil.getStatusBarHeight(this);
        llState.setLayoutParams(item_bar);
    }

    @Override
    protected void onDestroy() {
        if (searchList != null) {
            searchList.clear();
            searchList = null;
        }
        mList.clear();
        mList = null;
        super.onDestroy();
    }

    private void defultHistroyView() {
        for (final String search_text : searchList) {
            final TextView textview = (TextView) View.inflate(this, R.layout.item_search_history, null);
            textview.setText(search_text);
            textview.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    is_history = true;
                    etHomeSearch.setText(search_text);
                    etHomeSearch.setSelection(etHomeSearch.getText().length());
                    KeybordUtil.closeKeybord(HomeSearch_NewRetailActivity.this);

                    searchList.remove(searchList.indexOf(search_text));
                    searchList.add(0, search_text);
                    databaseAdaper.add(searchList);
                    wordWrapView.removeAllViews();
                    defultHistroyView();
                    setData();
                    page = 1;

                    keyWrod = search_text;
                    priceOrder = "";
                    salesOrder = "";
                    sort = 1;
                    requestShopList();
                    requestGoodsSortList(true,true);
                    //mPresenter.initSearchData(true, true,user_curent_lng,user_curent_lat, sid, page + "", limit + "", type + "", is_store, "", keyWrod, priceOrder, salesOrder, "");
                }
            });
            wordWrapView.addView(textview);
        }
        if (searchList.size() == 0) {
            rlSearchHistory.setVisibility(View.GONE);
        } else {
            rlSearchHistory.setVisibility(View.VISIBLE);
        }

    }


    @OnClick({R.id.iv_home_back, R.id.iv_home_search_et_delete, R.id.tv_home_search, R.id.iv_home_search_delete,
            R.id.tv_search_result_comprehensive_sequencing, R.id.tv_search_result_sales, R.id.tv_search_result_distance,
            R.id.tv_search_result_breaks_the_freight,R.id.rl_cart,
            R.id.img_openallshop,R.id.tv_all,R.id.rl_title})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_home_back:
                finish();
                break;
            case R.id.iv_home_search_et_delete:
                etHomeSearch.getText().clear();
                break;
            case R.id.tv_home_search:
                String search_text = etHomeSearch.getText().toString().trim();
                if (search_text.isEmpty()){
                    Utils.toastMessage(this,"请输入关键字");
                }else {
                    if (search_text.length() != 0) {
                        if (searchList.contains(search_text)) {
                            searchList.remove(searchList.indexOf(search_text));
                            searchList.add(0, search_text);
                        } else {
                            searchList.add(0, search_text);
                        }
                        databaseAdaper.add(searchList);
                        wordWrapView.removeAllViews();
                        defultHistroyView();
                        setData();
                    }
                    page = 1;

                    keyWrod = search_text;
                    priceOrder = "";
                    salesOrder = "";
                    sort = 1;
                    requestGoodsSortList(true,true);
                   // mPresenter.initSearchData(true, true, user_curent_lng, user_curent_lat, sid, page + "", limit + "", type + "", is_store, "", keyWrod, priceOrder, salesOrder, "");
                }
                break;
            case R.id.iv_home_search_delete:

                dialog.show();
                break;

            case R.id.tv_search_result_comprehensive_sequencing://综合排序
                if (!isComprehensiveSequencing) {
                    isComprehensiveSequencing = true;
                    isSales = false;
                    isDistance = false;
                    isPrice = false;
                    public_set();
                    page = 1;
                    priceOrder = "";
                    salesOrder = "";
                    //mPresenter.initSearchData(true, true, user_curent_lng,user_curent_lat,sid, page + "", limit + "", type + "", is_store, "", keyWrod, priceOrder, salesOrder, "");
                    sort = 1;
                    requestGoodsSortList(true,true);
                }
                break;
            case R.id.tv_search_result_sales://销量
                if (!isSales) {
                    isComprehensiveSequencing = false;
                    isSales = true;
                    isDistance = false;
                    isPrice = false;
                    public_set();
                    page = 1;
                    priceOrder = "";
                    salesOrder = "desc";
                    //mPresenter.initSearchData(true, true, user_curent_lng,user_curent_lat,sid, page + "", limit + "", type + "", is_store, "", keyWrod, priceOrder, salesOrder, "");
                    sort = 2;
                    requestGoodsSortList(true,true); }
                break;
            case R.id.tv_search_result_distance://距离
                //Toast.makeText(this, "距离功能暂未开放", Toast.LENGTH_SHORT).show();
                if (!isDistance) {
                    isComprehensiveSequencing = false;
                    isSales = false;
                    isDistance = true;
                    isPrice = false;
                    public_set();
                    page=1;
                    sort = 3;
                    requestGoodsSortList(true,true);
                }
                break;
            case R.id.tv_search_result_breaks_the_freight://价格
                if (!isPrice) {
                    isComprehensiveSequencing = false;
                    isSales = false;
                    isDistance = false;
                    isPrice = true;
                    public_set();
                    page=1;
                    sort = 4;
                    requestGoodsSortList(true,true);
                }
                break;

            case R.id.img_openallshop://查看所有店铺
                rl_openall.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_all://全部店铺商品
                storeId = "";
                requestGoodsSortList(true,true);
                tv_line.setVisibility(View.VISIBLE);
                tv_all.setTextColor(getResources().getColor(R.color.color_FE4e00));
                searShopDate.get(currentIndex).setCheck(false);
                hollayoutManager.smoothScrollToPosition(recycle_shop, new RecyclerView.State(), 0);
                searchShopListRetailAdapter.notifyDataSetChanged();
                //rl_openall.setVisibility(View.VISIBLE);
//                isOpen = !isOpen;
//                if (isOpen){
//                    rl_openall.setVisibility(View.VISIBLE);
//                }else {
//                    rl_openall.setVisibility(View.GONE);
//                }
                break;
            case R.id.rl_title://点击收起
                rl_openall.setVisibility(View.GONE);
                break;
            case R.id.rl_cart://购物车
                //购物车 跳转
                Intent intent = new Intent(this, GoodCarActivity.class);
                intent.putExtra("type", 0);
                startActivity(intent);
                break;
        }
    }

    /**
     * 点击历史，搜索
     */
    public void setData() {
        rlSearchHistory.setVisibility(View.INVISIBLE);
        rlHotSearchGoods.setVisibility(View.INVISIBLE);
        rlSearchType.setVisibility(View.VISIBLE);
        rvSearchItemType.setVisibility(View.GONE);

        isComprehensiveSequencing = true;
        isSales = false;
        isDistance = false;

        isBreaksTheFreight = false;
        isHighQualityStores = false;
        isMembersRedEnvelope = false;
        isCommentsHighMarks = false;
        public_set();

//        tvSearchResultBreaksTheFreight.setChecked(isBreaksTheFreight);
//        tvSearchResultHighQualityStores.setChecked(isHighQualityStores);
//        tvSearchResultMembersRedEnvelope.setChecked(isMembersRedEnvelope);
//        tvSearchResultCommentsHighMarks.setChecked(isCommentsHighMarks);

//        if (type == 0) {
//            tvSearchResultBreaksTheFreight.setVisibility(View.VISIBLE);
//            tvSearchResultHighQualityStores.setVisibility(View.VISIBLE);
//            tvSearchResultMembersRedEnvelope.setVisibility(View.VISIBLE);
//            tvSearchResultCommentsHighMarks.setVisibility(View.VISIBLE);
//        } else {
//            tvSearchResultBreaksTheFreight.setVisibility(View.GONE);
//            tvSearchResultHighQualityStores.setVisibility(View.GONE);
//            tvSearchResultMembersRedEnvelope.setVisibility(View.GONE);
//            tvSearchResultCommentsHighMarks.setVisibility(View.GONE);
//        }
    }

    @Override
    public void showLoading() {
        if (!ProgressDialog.getInstance().materialDialog.isShowing()) {
            ProgressDialog.getInstance().show(this);
        }
    }

    @Override
    public void hideLoading() {

            ProgressDialog.getInstance().dismiss();

    }

    @Override
    public void finishRefresh() {
        mRefreshLayout.finishRefresh(true);//刷新完成
    }

    @Override
    public void finishLoadMore() {
        mRefreshLayout.finishLoadMore(true);//加载完成
    }

    @Override
    public void onError(Throwable throwable) {
        Toast.makeText(this, "网络请求出错", Toast.LENGTH_SHORT).show();
        Log.e("throwable",throwable.toString());
    }


    /**
     * 搜索出的类别与店铺列表
     *
     * @param bean
     */
    @Override
    public void onInitDataSuccess(SearchBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            searchItemAdapter.setData(bean,etHomeSearch.getText().toString().trim());
            searchItemAdapter.setOnItemClickListener(new ItemClickListener() {
                @Override
                public void onItemClick(int position) {

                    page = 1;
                    keyWrod = bean.getData().getGoods().get(position).getTitle();
                    etHomeSearch.setText(keyWrod);
                    etHomeSearch.setSelection(keyWrod.length());
                    if (keyWrod.length() != 0) {
                        if (searchList.contains(keyWrod)) {
                            searchList.remove(searchList.indexOf(keyWrod));
                            searchList.add(0, keyWrod);
                        } else {
                            searchList.add(0, keyWrod);
                        }
                        databaseAdaper.add(searchList);
                        wordWrapView.removeAllViews();
                        defultHistroyView();
                        setData();
                    }
                    //priceOrder    按价格排序 desc/asc
                    //salesOrder    按销售量排序 desc/asc
                    //news    是否是新品 1是 0否
                    priceOrder = "";
                    salesOrder = "";
                  //  mPresenter.initSearchData(true, true,user_curent_lng,user_curent_lat, sid, page + "", limit + "", type + "", is_store, "", keyWrod, priceOrder, salesOrder, "");
                    //请求店铺列表
                    requestShopList();
                    //请求商品排序列表
                    requestGoodsSortList(true,true);
                }
            });
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    //请求商品排序列表
    private void requestGoodsSortList(boolean isRefresh,boolean isLoading) {
        Map<String,Object> goodsmap = new HashMap<>();
        goodsmap.put("storeId",storeId);
        goodsmap.put("sort",sort);
        goodsmap.put("lng",user_curent_lng);
        goodsmap.put("lat",user_curent_lat);
        goodsmap.put("page",page);
        goodsmap.put("limit",limit);
        goodsmap.put("keyWord",keyWrod);
        mPresenter.getSearchGoodsList(isRefresh,isLoading,goodsmap);
        tv_shopabout.setText("\""+keyWrod+"\"");
    }

    //请求店铺列表
    private void requestShopList() {
        Map<String, Object> map = new HashMap<>();
        map.put("keyWord", keyWrod);
        map.put("lng", user_curent_lng);
        map.put("lat", user_curent_lat);
        mPresenter.getSearchShopList(map);
        tv_shopabout.setText("\"" + keyWrod + "\"");
    }

    @Override
    public void onHotSearchSuccess(HotSearchBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            for (final String search_text : bean.getData()) {
                final TextView textview = (TextView) View.inflate(this, R.layout.item_search_history, null);
                textview.setText(search_text);
                textview.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        is_history = true;
                        etHomeSearch.setText(search_text);
                        etHomeSearch.setSelection(etHomeSearch.getText().length());
                        KeybordUtil.closeKeybord(HomeSearch_NewRetailActivity.this);

                        searchList.add(0, search_text);
                        databaseAdaper.add(searchList);
                        wordWrapView.removeAllViews();
                        defultHistroyView();
                        setData();
                        page = 1;

                        keyWrod = search_text;
                        priceOrder = "";
                        salesOrder = "";

                        //请求店铺列表
                        requestShopList();
                        //请求商品排序列表
                        requestGoodsSortList(true,true);
                       // mPresenter.initSearchData(true, true, user_curent_lng,user_curent_lat,sid, page + "", limit + "", type + "", is_store, "", keyWrod, priceOrder, salesOrder, "");
                    }
                });
                wwViewResou.addView(textview);
            }
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * @param bean
     */
    @Override
    public void onInitSearchDataSuccess(HomeSearchXFDGoodBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (page == 1) {
                mList.clear();
                mRefreshLayout.setNoMoreData(false);
                mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                    @Override
                    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                        mPresenter.initSearchData(false, false,user_curent_lng,user_curent_lat, sid, page + "", limit + "", type + "", is_store, "", keyWrod, priceOrder, salesOrder, "");

                    }
                });
            }
            if (bean.getData().size() == 0) {
                if (page == 1) {
                    llHint.setVisibility(View.VISIBLE);
                    tvHint.setText("没有找到"+etHomeSearch.getText().toString().trim());
                }
                mRefreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                page++;
                mList.addAll(bean.getData());
                searchShopsAdapter.notifyDataSetChanged();
            }
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onGetSearchShopListSuccess(SearchShopBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            searShopDate = bean.getData();
            searShopDate.add(0,new SearchShopBean.DataBean(0,"全部"));
            searShopDate.get(0).setCheck(true);
            searchShopListRetailAdapter.refreshDatas(searShopDate);
            searchShopListRetailOpenAllAdapter.refreshDatas(searShopDate);
            if (EmptyUtil.isNotEmpty(searShopDate)){
                tv_shopcount.setText(searShopDate.size()+"个商家有");
            }

        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onGetSearchGoodsListSuccess(HomeSearchRetailGoodsBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            //搜索完成显示购物车，隐藏搜索按钮
            tvHomeSearchCancel.setVisibility(View.GONE);
            rl_cart.setVisibility(View.VISIBLE);
            if (bean.getData().getCartCount()==0){
                tv_allgoodscount.setVisibility(View.GONE);
            }else {
                tv_allgoodscount.setVisibility(View.VISIBLE);
                tv_allgoodscount.setText(bean.getData().getCartCount()+"");
            }
            if (page == 1) {
                mList.clear();
                mRefreshLayout.setNoMoreData(false);
                mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                    @Override
                    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                        //请求商品排序列表
                        requestGoodsSortList(false,true);

                        //mPresenter.initSearchData(false, false,user_curent_lng,user_curent_lat, sid, page + "", limit + "", type + "", is_store, "", keyWrod, priceOrder, salesOrder, "");

                    }
                });

                if (EmptyUtil.isNotEmpty(bean.getData().getGoods())){
                    searchGoodsListRetailAdapter.refreshDatas(bean.getData().getGoods());
                }else {
                    llHint.setVisibility(View.VISIBLE);
                    tvHint.setText("没有找到"+etHomeSearch.getText().toString().trim());
                }
            }else {
                if (bean.getData().getGoods().size() == 0) {
                    if (page == 1) {
                        llHint.setVisibility(View.VISIBLE);
                        tvHint.setText("没有找到"+etHomeSearch.getText().toString().trim());
                    }
                    mRefreshLayout.finishLoadMoreWithNoMoreData();
                } else {
                    page++;
                    //mList.addAll(bean.getData());
                    searchGoodsListRetailAdapter.addData(bean.getData().getGoods());
                    // searchShopsAdapter.notifyDataSetChanged();
                }
            }

        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onAddCarSuccess(ConfirmGoodBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            searchGoodsList.get(currentListIndex).setCartCount(searchGoodsList.get(currentListIndex).getCartCount()+1);
            searchGoodsListRetailAdapter.setData(currentListIndex,searchGoodsList.get(currentListIndex));
           // tv_allgoodscount.setText(bean.getData().getCount().get);
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        } else {
            if (bean.getStatus() == Constants.LOGIN_CODE) {
                UtilsData.getPreference(this, "login").remove("head_url");
                UtilsData.getPreference(this, "login").remove("nickname");
                UtilsData.getPreference(this, "login").remove("is_store");
                UtilsData.getPreference(this, "login").remove("token");
                APP_TOKEN = "";
                Intent intent = new Intent(this, OneLoginMainActivity.class);
                startActivity(intent);
                return;
            }
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onGetRetailHotSearchSuccess(HotSearchRetailBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            hotSearch = bean.getData();
            searchHotRetailListAdapter.refreshDatas(hotSearch);

            searchHotRetailListAdapter.setItemClickListener(new SearchHotRetailListAdapter.OnItemOnClickListener() {
                @Override
                public void onItemClick(int position, HotSearchRetailBean.DataBean date) {
                    searchTitle = date.getName();
                    is_history = true;
                    etHomeSearch.setText(searchTitle);
                    etHomeSearch.setSelection(etHomeSearch.getText().length());
                    KeybordUtil.closeKeybord(HomeSearch_NewRetailActivity.this);

                    searchList.add(0, searchTitle);
                    databaseAdaper.add(searchList);
                    wordWrapView.removeAllViews();
                    defultHistroyView();
                    setData();
                    page = 1;

                    keyWrod = searchTitle;
                    priceOrder = "";
                    salesOrder = "";

                    //请求店铺列表
                    requestShopList();
                    //请求商品排序列表
                    requestGoodsSortList(true,true);
                }
            });

        } else {

            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    private void public_set() {
        tvSearchResultComprehensiveSequencing.setChecked(isComprehensiveSequencing);
        tvSearchResultSales.setChecked(isSales);
        tvSearchResultDistance.setChecked(isDistance);
        tvSearchResultPrice.setChecked(isPrice);
    }


}
